package cn.dao.impl;

import cn.dao.BaseDao;
import cn.dao.DistrictDao;
import cn.entity.District;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Dao层接口的实现类
 * @author yale
 * @create 2017/10/9
 * @version 0.1
 */
public class DistrictDaoImpl extends BaseDao implements DistrictDao {

    /**
     * 查询所有数据
     * @return
     */
    @Override
    public List<District> findByAll() {
        ResultSet rSet = null;
        String sql = "select * from district";
        rSet = super.findAll(sql, null);
        List<District> list = new ArrayList<District>();
        try {
            while (rSet.next()) {
                //封装数据
                District dis = new District();
                dis.setId(rSet.getInt(1));
                dis.setName(rSet.getString(2));

                list.add(dis);
            }
        } catch (SQLException e){
            e.printStackTrace();
        } finally{
            //super.close();//父类
        }
        return list;
    }

    @Override
    public int add(District dst) {
        String sql = "insert into district(id,name) value (?,?)";
        String params[] = new String[2];
        params[0] = ""+dst.getId();
        params[1] = dst.getName();
        int result = super.op(sql, params);
        return result;
    }

    @Override
    public int delete(District dst) {
        String sql = "delete from district where id = ?";
        String params[] = new String[1];
        params[0] = ""+dst.getId();
        int result = super.op(sql, params);
        return result;
    }

    @Override
    public int update(District dst) {

        return 0;
    }

    @Override
    public District findById(int id) {
        String sql = "select * from district where id = ?";
        String params[] = new String[]{""+id};// new String []{""+id}
        ResultSet result = super.findAll(sql, params);
        District dist = null;
        try {
            while (result.next()) {
                dist = new District();
                dist.setId(result.getInt(1));
                dist.setName(result.getString(2));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return dist;
    }
}
